<template>
    <div>
           <div class="search-term">
                    <el-form :inline="true" :model="searchInfo" class="demo-form-inline">
                        <el-form-item label="路线始终点">
                            <el-input placeholder="搜索条件" @keyup.native.enter="onSubmit" clearable v-model="searchInfo.LineName"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button @click="onSubmit" type="primary">查询</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button @click="openDialog" type="primary">新增路线</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-popover placement="top" v-model="deleteVisible" width="160">
                                <p>确定要删除吗？</p>
                                <div style="text-align: right; margin: 0">
                                    <el-button @click="deleteVisible = false" size="mini" type="text">取消</el-button>
                                    <el-button @click="onDelete" size="mini" type="primary">确定</el-button>
                                </div>
                               <!-- <el-button icon="el-icon-delete" size="mini" slot="reference" type="danger">批量删除</el-button>-->
                            </el-popover>
                        </el-form-item>
                    </el-form>
                </div>

            <el-table
                    default-expand-all
                    @row-click="rowClick"
                    :data="tableData"
                    @selection-change="handleSelectionChange"
                    border
                    ref="multipleTable"
                    stripe
                    style="width: 100%"
                    tooltip-effect="dark"
            >
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column type="expand" width="55">
                    <template slot-scope="scope">
                        <el-steps :active="scope.row.tails.length" style="margin-top: 20px" align-center>
                            <el-step v-for="(item, index) in scope.row.tails" :key="index" :title="item.station" :description="item.step_time"></el-step>
                        </el-steps>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="创建日期" width="280">
                    <template slot-scope="scope">{{scope.row.CreatedAt|formatDate}}</template>
                </el-table-column>

                <el-table-column align="center" label="路线始终点" prop="line_name" width="280"></el-table-column>

                <el-table-column align="center" label="按钮组">
                    <template slot-scope="scope">
                        <el-button class="table-button" @click="handleToUpdateTails(scope.row)" size="small" type="success" icon="el-icon-info">管理站点</el-button>
                        <el-button class="table-button" @click="updateLines(scope.row)" size="small" type="primary" icon="el-icon-s-help">路线变更</el-button>
                        <el-button type="warning" icon="el-icon-s-promotion" size="mini">地图导航</el-button>
                       <!-- <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRow(scope.row)">删除</el-button>-->
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination
                    :current-page="page"
                    :page-size="pageSize"
                    :page-sizes="[10, 30, 50, 100]"
                    :style="{float:'right',padding:'20px'}"
                    :total="total"
                    @current-change="handleCurrentChange"
                    @size-change="handleSizeChange"
                    layout="total, sizes, prev, pager, next, jumper"
            ></el-pagination>

            <el-dialog :before-close="closeDialog" :visible.sync="dialogFormVisible" title="弹窗操作">
                <el-form :model="formData" label-position="right" label-width="120px">
                    <el-form-item label="路线始终点:">
                        <el-input @keyup.native.enter="enterDialog" v-model="formData.line_name" clearable placeholder="请输入" ></el-input>
                    </el-form-item>
                </el-form>
                <div class="dialog-footer" slot="footer">
                    <el-button @click="closeDialog">取 消</el-button>
                    <el-button @click="enterDialog" type="primary">确 定</el-button>
                </div>
            </el-dialog>

            <el-drawer
                style="overflow-y:auto;overflow-x:hidden;"
                size="70%"
                :visible.sync="drawer"
                :direction="direction"
        >

                <div style="width: 800px">
                    <el-tag style="margin-top: -50px; width: 110px; margin-left: 30px;float: left" effect="dark">当前路线始终点</el-tag>
                    <el-steps active="2" style="margin-top: -50px; width: 240px; margin-left: 300px;float: left;">
                        <el-step :title="startStation" icon="el-icon-s-help"></el-step>
                        <el-step :title="toStation" icon="el-icon-help"></el-step>
                    </el-steps>
                    <el-popover
                            placement="right"
                            title="添加站点"
                            width="400"
                            trigger="click"
                    >
                        <el-form ref="tailForm" :model="tailForm" label-width="100px">
                            <el-form-item label="站点名称">
                                <el-input v-model="tailForm.station"></el-input>
                            </el-form-item>
                            <el-form-item label="开始候车时间">
                                <el-time-select
                                        v-model="tailForm.wait_time"
                                        :picker-options="{
                    start: '08:30',
                    step: '00:15',
                    end: '18:30'
                  }"
                                        placeholder="选择时间">
                                </el-time-select>
                            </el-form-item>
                            <el-form-item label="继续发车时间">
                                <el-time-select
                                        v-model="tailForm.continue_time"
                                        :picker-options="{
                    start: '08:30',
                    step: '00:15',
                    end: '18:30'
                  }"
                                        placeholder="选择时间">
                                </el-time-select>
                            </el-form-item>
                            <el-form-item label="下车时间">
                                <el-input v-model="tailForm.step_time"></el-input>
                            </el-form-item>
                            <el-form-item>
                                <el-button @click="addTails" size="small" type="success">立即创建</el-button>
                            </el-form-item>
                        </el-form>
                        <el-button slot="reference" @click="handleToAddTails" style="margin-top: -50px; margin-left: 200px; float: left" type="success" icon="el-icon-plus" circle></el-button>
                    </el-popover>
                </div>

               <el-table style="margin-left: 30px; width: 800px; margin-top: 20px" :data="tailsList">
                <el-table-column label="站点" prop="station" width="160" align="center" />
                <el-table-column label="候车时间" prop="wait_time" width="160" align="center" />
                <el-table-column label="继续发车时间" prop="continue_time" width="160" align="center" />
                   <el-table-column label="站点上下车时间" prop="step_time" width="140" align="center" >
                       <template slot-scope="scope">
                           {{ scope.row.step_time }} 分
                       </template>
                   </el-table-column>
                <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <el-popover
                                placement="right"
                                title="编辑站点"
                                width="400"
                                trigger="click"
                        >
                            <el-form ref="tailForm" :model="tailForm" label-width="100px">
                                <el-form-item label="站点名称">
                                    <el-input v-model="tailForm.station"></el-input>
                                </el-form-item>
                                <el-form-item label="开始候车时间">
                                    <el-time-select
                                            v-model="tailForm.wait_time"
                                            :picker-options="{
                        start: '08:30',
                        step: '00:15',
                        end: '18:30'
                      }"
                                            placeholder="选择时间">
                                    </el-time-select>
                                </el-form-item>
                                <el-form-item label="继续发车时间">
                                    <el-time-select
                                            v-model="tailForm.continue_time"
                                            :picker-options="{
                        start: '08:30',
                        step: '00:15',
                        end: '18:30'
                      }"
                                            placeholder="选择时间">
                                    </el-time-select>
                                </el-form-item>
                                <el-form-item label="下车时间">
                                    <el-input v-model="tailForm.step_time"></el-input>
                                </el-form-item>
                                <el-form-item>
                                    <el-button @click="updateTails" size="small" type="primary">更新站点</el-button>
                                </el-form-item>
                            </el-form>
                            <el-button @click="handleUpdateTails(scope.row)" slot="reference" size="small" type="primary" icon="el-icon-edit" >编辑站点</el-button>
                        </el-popover>
                        <!--<el-button style="margin-left: 20px" @click="handleDelete(scope.row)" type="danger" icon="el-icon-delete" circle></el-button>-->
                    </template>
                </el-table-column>
            </el-table>

            <!--        <pagination
                      v-show="total>0"
                      :total="total"
                      :page.sync="queryParams.pageNum"
                      :limit.sync="queryParams.pageSize"
                      @pagination=""
                    />-->

        </el-drawer>

    </div>
</template>

<script>
    import {
        createLines,
        deleteLines,
        deleteLinesByIds,
        updateLines,
        findLines,
        getLinesList
    } from "@/api/lines";  //  此处请自行替换地址
    import { formatTimeToStr } from "@/utils/date";
    import infoList from "@/mixins/infoList";
    import {
        createTails,
        getTailsByMaxCreateTimeWhereLineId,
        getTailsListByLineId,
        updateTails
    } from "../../../api/tails";
    import {createLinesTails} from "../../../api/linesTails";
    export default {
        name: "Lines",
        mixins: [infoList],
        data() {
            return {
                startStation: '',
                toStation: '',
                rowLinesId: '', // 行路线
                tailForm: {
                    id: undefined,
                    station: '',
                    wait_time: '',
                    continue_time: '',
                    step_time: '',
                    lines_id: '',
                },
                direction: 'rtl',
                tailsList: [], // 站点数组
                activeName: 'first',
                drawer: false,
                listApi: getLinesList,
                dialogFormVisible: false,
                type: "",
                deleteVisible: false,
                multipleSelection: [],
                formData: {
                    line_name:"",
                },
                linesTailsForm: {
                    LinesId: '',
                    TailsId: '',
                }
            };
        },
        filters: {
            formatDate: function(time) {
                if (time != null && time != "") {
                    var date = new Date(time);
                    return formatTimeToStr(date, "yyyy-MM-dd hh:mm:ss");
                } else {
                    return "";
                }
            },
            formatBoolean: function(bool) {
                if (bool != null) {
                    return bool ? "是" :"否";
                } else {
                    return "";
                }
            }
        },
        watch: {
          'drawer'(newValue, oldValue) {
              if (newValue === false) {
                  this.getTableData()
              }
          }
        },
        methods: {
            // 更新站点确认
            updateTails() {
                updateTails(this.tailForm).then(res => {
                    if (res.code === 0) {
                        this.$message.success('更新站点成功')
                        // 更新路线对应的站点列表
                        getTailsListByLineId({ LinesId: this.rowLinesId }).then(response => {
                            this.tailsList = response.data.list
                        })
                    }
                })
            },
            // 编辑站点控制
           async handleUpdateTails(row) {
                this.tailForm = row
            },
            // 管理站点控制
            async handleToUpdateTails(row) {
                this.rowLinesId = row.ID // 行路线
                const res = await getTailsListByLineId({ LinesId: row.ID });
                this.drawer = true
                console.log('根据LinesId查询数据列表')
                console.log(res)
                this.tailsList = res.data.list

                this.startStation = res.data.list[0].station
                this.toStation = res.data.list[res.data.list.length-1].station
            },
            // 创建站点控制
            handleToAddTails() {
              this.tailForm = {}
            },
            // 创建站点确认
            addTails() {
                this.tailForm.lines_id = this.rowLinesId
                console.log(this.tailForm)
                createTails(this.tailForm).then(res => {
                    console.log(res)
                    if (res.code === 0) {
                        this.$message.success('创建成功')

                        // 根据LineId的最大创建时间查询最新记录
                        getTailsByMaxCreateTimeWhereLineId({ LinesId: this.rowLinesId }).then(resp => {
                            console.log('根据LineId的最大创建时间查询最新记录')
                            console.log(resp.data.newTails)
                            // 更新路线站点中间表
                            this.linesTailsForm.LinesId = this.rowLinesId
                            this.linesTailsForm.TailsId = resp.data.newTails.ID
                            createLinesTails(this.linesTailsForm).then(result => {
                                console.log('更新路线站点中间表')
                                console.log(result)
                            } )
                        })

                    }
                    // 更新路线对应的站点列表
                    getTailsListByLineId({ LinesId: this.rowLinesId }).then(response => {
                        this.tailsList = response.data.list

                        this.startStation = response.data.list[0].station
                        this.toStation = res.data.list[res.data.list.length-1].station

                    })
                })
            },
            rowClick(data) {
              console.log('行数据')
              console.log(data)
            },
            //条件搜索前端看此方法
            onSubmit() {
                this.page = 1
                this.pageSize = 10
                this.getTableData()
            },
            handleSelectionChange(val) {
                this.multipleSelection = val
            },
            deleteRow(row){
                this.$confirm('确定要删除吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.deleteLines(row);
                });
            },
            async onDelete() {
                const ids = []
                if(this.multipleSelection.length == 0){
                    this.$message({
                        type: 'warning',
                        message: '请选择要删除的数据'
                    })
                    return
                }
                this.multipleSelection &&
                this.multipleSelection.map(item => {
                    ids.push(item.ID)
                })
                const res = await deleteLinesByIds({ ids })
                if (res.code == 0) {
                    this.$message({
                        type: 'success',
                        message: '删除成功'
                    })
                    if (this.tableData.length == ids.length) {
                        this.page--;
                    }
                    this.deleteVisible = false
                    this.getTableData()
                }
            },
            async updateLines(row) {
                const res = await findLines({ ID: row.ID });
                this.type = "update";
                if (res.code == 0) {
                    this.formData = res.data.relines;
                    this.dialogFormVisible = true;
                }
            },
            closeDialog() {
                this.dialogFormVisible = false;
                this.formData = {
                    lines:"",

                };
            },
            async deleteLines(row) {
                const res = await deleteLines({ ID: row.ID });
                if (res.code == 0) {
                    this.$message({
                        type: "success",
                        message: "删除成功"
                    });
                    if (this.tableData.length == 1) {
                        this.page--;
                    }
                    this.getTableData();
                }
            },
            async enterDialog() {
                let res;
                switch (this.type) {
                    case "create":
                        res = await createLines(this.formData);
                        break;
                    case "update":
                        res = await updateLines(this.formData);
                        break;
                    default:
                        res = await createLines(this.formData);
                        break;
                }
                if (res.code == 0) {
                    this.$message({
                        type:"success",
                        message:"创建/更改成功"
                    })
                    this.closeDialog();
                    this.getTableData();
                }
            },
            openDialog() {
                this.type = "create";
                this.dialogFormVisible = true;
            }
        },
        async created() {
            await this.getTableData();
        }
    };
</script>

<style>
    .el-drawer{
        overflow: scroll
    }
</style>
